package mz.matafe.bolao

/**
 * Domain Class for a Cup.
 *
 * <p>Represents a Cup. Eg.: (South Africa World Cup 2010)
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class Cup implements Comparable{

    //services
    def authenticateService

    //properties
    Integer year
    String venue
    Date dateCreated
    Date lastUpdated
    User createdBy
    User updatedBy
    boolean active = true
    
    static hasMany = [groups : Group]

    static constraints = {
        year(unique:true, validator: {
                it.toString().length() == 4
            })
        venue(blank:false, size:1..50)
        dateCreated()
        lastUpdated()
        createdBy(nullable:true)
        updatedBy(nullable:true)
        active()
    }

    static mapping = {
        table 'WC_CUP'
        groups sort:'name'
        createdBy column: 'CREATED_BY'
        updatedBy column: 'UPDATED_BY'
    }

    def beforeInsert = {
        log.info "Before insert a Cup"
        def loggedUser = authenticateService.userDomain()
        this.createdBy = this.createdBy ?: loggedUser
        this.updatedBy = updatedBy ?: loggedUser
    }

    def beforeUpdate = {
        log.info "Updating cup ${id} "
        this.updatedBy = authenticateService.userDomain()
    }

    def afterInsert = {
        log.info "Cup ${id} inserted by ${createdBy}"
    }

    def afterUpdate = {
        log.info "Cup ${id} updated by ${updatedBy}"
    }

    String toString(){
        "${this.class.name}:id[$id];year[$year]"
    }

    int compareTo(Object o){
        this.id <=> ((Cup)o).id
    }
}
